package com.coalmine.api.controller;

import com.coalmine.api.domain.ApiApprove;
import com.coalmine.api.domain.ApiConfig;
import com.coalmine.api.domain.ApiToken;
import com.coalmine.api.domain.resp.GetAllApplyUserRespVO;
import com.coalmine.api.service.IApiApproveService;
import com.coalmine.api.service.IApiConfigService;
import com.coalmine.api.service.IApiTokenService;
import com.coalmine.common.annotation.Log;
import com.coalmine.common.constant.HttpStatus;
import com.coalmine.common.core.controller.BaseController;
import com.coalmine.common.core.domain.AjaxResult;
import com.coalmine.common.core.page.TableDataInfo;
import com.coalmine.common.enums.BusinessType;
import com.coalmine.common.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * api的审批信息表 前端控制器
 * </p>
 *
 * @author wsf
 * @since 2022-06-02
 */
@Slf4j
@Api(tags = "API-审批管理接口")
@RestController
@RequestMapping("/api/approve")
public class ApiApproveController extends BaseController {
    @Autowired
    IApiApproveService iApiApproveService;

    @Autowired
    private IApiConfigService apiConfigService;

    @Autowired
    IApiTokenService tokenService;

    @ApiOperation("获取所有审批")
    @PreAuthorize("@ss.hasPermi('api:approve:all')")
    @GetMapping("/getAllApprove")
    @Deprecated // 使用list接口
    public TableDataInfo getAllApprove() {
        startPage();
        List<ApiApprove> apiApproveList = iApiApproveService.getAll();
        return getDataTable(apiApproveList);
    }

    @ApiOperation("根据id获取审批详情")
    @PreAuthorize("@ss.hasPermi('api:approve:query')")
    @GetMapping("/findApproveById/{approveId}")
    public AjaxResult findApproveById(@PathVariable String approveId) {
        ApiApprove apiApprove = iApiApproveService.findApproveById(approveId);
        ApiToken token = tokenService.getTokenById(apiApprove.getTokenId());
        ApiConfig apiConfig = apiConfigService.getById(apiApprove.getApiId());
        if (token != null) {
            apiApprove.setApplyUserName(token.getNote());
        }
        if (apiConfig != null) {
            apiApprove.setApiName(apiConfig.getName());
        }
        return AjaxResult.success(apiApprove);
    }

    @PreAuthorize("@ss.hasPermi('api:approve:edit')")
    @ApiOperation("根据id处理审批")
    @Log(title = "审批处理", businessType = BusinessType.UPDATE)
    @PutMapping("/updateApproveById")
    public AjaxResult updateApproveById(@RequestBody ApiApprove approve) {
        return iApiApproveService.updateApproveById(approve);
    }

    @ApiOperation("获取申请用户列表")
    @GetMapping("/getAllApplyUser")
    public AjaxResult getAllApplyUser() {
        List<ApiApprove> allToken = iApiApproveService.getAllApplyUser();
        if (allToken.size() == 0) {
            return AjaxResult.success("暂无数据");
        }
        Set<String> tokenIds = allToken.stream().map(ApiApprove::getTokenId).collect(Collectors.toSet());
        List<ApiToken> tokenList = tokenService.listByIds(tokenIds);
        List<GetAllApplyUserRespVO> data = new ArrayList<>();
        tokenList.stream()
                .filter(t -> StringUtils.isNotEmpty(t.getNote()))
                .forEach(t -> {
            data.add(new GetAllApplyUserRespVO(t.getId(), t.getNote()));
        });
        return AjaxResult.success(data);
    }

    @ApiOperation("列表下拉框查询")
    @GetMapping("/list")
    public TableDataInfo list(String applyUserId, String groupId, Integer approveType) {
        startPage();
        List<ApiApprove> apiApproves = iApiApproveService.select(applyUserId, groupId, approveType);
        List<String> tokenIds = apiApproves.stream().map(ApiApprove::getTokenId).collect(Collectors.toList());
        List<String> apiIds = apiApproves.stream().map(ApiApprove::getApiId).collect(Collectors.toList());
        if (tokenIds.size() == 0 || apiIds.size() == 0) {
            TableDataInfo data = new TableDataInfo();
            data.setCode(HttpStatus.SUCCESS);
            data.setMsg("暂无数据");
            return data;
        }
        List<ApiToken> tokenList = tokenService.listByIds(tokenIds);
        Map<String, String> tokenIdNameMap = tokenList.stream()
                .filter(t -> StringUtils.isNotEmpty(t.getName()))
                .collect(Collectors.toMap(ApiToken::getId, ApiToken::getName));
        Map<String, String> tokenIdNoteMap = tokenList.stream()
                .filter(t -> StringUtils.isNotEmpty(t.getNote()))
                .collect(Collectors.toMap(ApiToken::getId, ApiToken::getNote));

        List<ApiConfig> apiConfigList = apiConfigService.listByIds(apiIds);
        Map<String, String> apiNameMap = apiConfigList.stream()
                .collect(Collectors.toMap(ApiConfig::getId, ApiConfig::getName));
        apiApproves.stream().forEach(a -> {
            if (tokenIdNoteMap.containsKey(a.getTokenId())) {
                a.setApplyUserName(tokenIdNoteMap.get(a.getTokenId()));
            }
            if (tokenIdNameMap.containsKey(a.getTokenId())) {
                a.setTokenName(tokenIdNameMap.get(a.getTokenId()));
            }
            if (apiNameMap.containsKey(a.getApiId())) {
                a.setApiName(apiNameMap.get(a.getApiId()));
            }
        });
        return getDataTable(apiApproves);
    }
}


